package com.framework.base.util; 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;

import com.framework.base.dao.IDManager;
import com.framework.main.sys.attachment.domain.AttachmentVo;

/**
 * Description:功能描述
 * tabaleName(对应的表名):
 * Company: framework
 * @author：HYH
 * @version 1.0
 * @Date 2011-6-17 上午09:14:30
 */
public class FileUtil {
	public static String rootPath=SysConfUtil.getUpLoadPath();
	public static final boolean isExistDir=false;
	public static String monthDirName="";//附件存储月目录
	public static final String tempDirName="tempDir"; //用于存储临时文件 

	/**
	 * 获取文件格式
	 * @param fileName 文件名
	 * @return
	 */
	public static String getFileFormat(String fileName){
		if(fileName != null && fileName.trim().length() > 0){
			int pos = fileName.lastIndexOf(".");
			if(pos > 0)
			return fileName.substring(pos + 1);
		}
		return "";
	}
	
	/**
	 * 获取文件名（不含后缀名）
	 * @param fileName 文件名
	 * @return
	 */
	public static String getFileNameWithNoFormat(String fileName){
		if(fileName != null && fileName.trim().length() > 0){
			int pos = fileName.lastIndexOf(".");
			return fileName.substring(0, pos);
		}
		return "";
	}


	
	/**
	 * 格式化文件路径
	 * @param path
	 * @return
	 */
	public static String formatPath(String path) {
		if(path != null && path.trim().length() > 0){
			// 将一个或多个“\”转化成“/”
			path = path.replaceAll("\\\\{1,}", "/");
			// 将多个“/”转化成一个“/”
			path = path.replaceAll("\\/{2,}", "/");
		}
	   return path;
	}
	
	/**
	 * 判断两个文件的整个路径（文件路径+文件名）是否相同
	 * @param filePath1 文件路径1
	 * @param fileName1 文件名1
	 * @param filePath2 文件路径2
	 * @param fileName2 文件名2
	 * @param isNeedToFormatPath 是否需要格式化文件路径
	 * @return
	 */
	public static boolean isTwoPathSame(String filePath1, String fileName1, String filePath2, String fileName2, boolean isNeedToFormatPath){
		if((filePath1 == null || filePath1.trim().length() <= 0) 
			|| (fileName1 == null || fileName1.trim().length() <= 0)
			|| (filePath2 == null || filePath2.trim().length() <= 0)
			|| (fileName2 == null || fileName2.trim().length() <= 0)){
			return false;
		}
		
		if(isNeedToFormatPath){
			filePath1 = formatPath(filePath1);
			filePath2 = formatPath(filePath2);
		}
		
		String fileWholePath1 = filePath1 + fileName1;
		String fileWholePath2 = filePath2 + fileName2;
		return fileWholePath1.equalsIgnoreCase(fileWholePath2);
	}
	
	/**
	 * 处理文件上传到服务器
	 * @param files 需要上传的文件数组
	 * @param isTemp 是否是临时文件 默认为false
	 * @return 所有的磁盘文件名
	 * @throws Exception
	 */
	public static List<AttachmentVo>  doUploadFile(List<AttachmentVo> attachsList) throws Exception{
		return doUploadFile(attachsList,false,null,null);
	}
	
	/**
	 * 处理文件上传到服务器
	 * @param files 需要上传的文件数组
	 * @param isTemp 是否是临时文件 默认为false
	 * @return 所有的磁盘文件名
	 * @throws Exception
	 */
	public static List<AttachmentVo>  doUploadFile(List<AttachmentVo> attachs,boolean isTemp,String activityIdf,String activityNamef) throws Exception{
		activityIdf=StringUtil.getStringFromObj(activityIdf);
		activityNamef=StringUtil.getStringFromObj(activityNamef);
		List<AttachmentVo> resultAttachmentVoList=new ArrayList<AttachmentVo>();
		if(attachs==null){
			return resultAttachmentVoList;
		}
		String subDirName=isTemp?tempDirName:DateUtil.getYM();
		//1.如果是根文件不存在则创建
		if(!isTemp){
			rootPath=formatPath(rootPath);
			File dirFile=new File(rootPath+"\\"+tempDirName);
			System.out.println("=="+dirFile.exists());
			if(!dirFile.exists()){
				dirFile.mkdir();
			}
		}
		//2.判断分月存储的子目录是否存在 不存在则创建
		if(!isTemp&&!monthDirName.equals(DateUtil.getYM())){
			String monthDri=formatPath(rootPath+"\\"+DateUtil.getYM());
			File monthDir=new File(monthDri);
			if(!monthDir.exists()){
				monthDir.mkdir();
			}
			monthDirName=DateUtil.getYM();
		}
		//3.上传文件
		for (AttachmentVo attachmentVo : attachs) {
			String diskFileName=subDirName+"\\"+IDManager.generateID()+"."+getFileFormat(attachmentVo.getFileNamef());
			attachmentVo.setActivityIdf(activityIdf);
			attachmentVo.setActivityName(activityNamef);
			attachmentVo.setDiskFilePathf(diskFileName);
			FileUtils.copyFile(attachmentVo.getFile(), new File(rootPath+"\\"+diskFileName));
			resultAttachmentVoList.add(attachmentVo);
		}
		return resultAttachmentVoList; 
	}
	/**
	 * 用于读取文件内容
	 * @param diskFileName 磁盘文件名
	 * @return 
	 */
	public static InputStream getFileInputStream(String diskFileName){
		String fullPath=rootPath+"\\"+diskFileName;
		try {
			return new FileInputStream(new File(formatPath(fullPath)));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		
	}
	/**
	 * 判断文件名是否合法
	 * @param fileName
	 * @return
	 */
	public static boolean isFileNameValid(String fileName){
		if(fileName == null || fileName.trim().length() <= 0)
			return false;
		
		String[] errorStr =new String []{"/","\\",":",",","*","?","\"","<",">","|"};
		
		for(int i = 0; i < errorStr.length; i++){
			if(fileName.contains(errorStr[i]))
				return false;
		}
		return true;
		
	}
	

	
	/**
	 * 根据文件的扩展名，获取模板文件
	 * @param extentFileName 文件的扩展名
	 * @param templateFilePath office模板文件的存放的绝对路径
	 * @return
	 */
	private static String getTemplateFileWholePath(String extentFileName, String templateFilePath){
		String templateFile = null;
    	
    	if(extentFileName != null && extentFileName.trim().length() > 0){
    		
    		extentFileName = extentFileName.toLowerCase();
    		
    		if(extentFileName.equals("xls")){
        		templateFile = templateFilePath + "\\" + "newExcelTemplate.xls";
        	}
        	else if(extentFileName.equals("ppt")){
        		templateFile = templateFilePath + "\\" + "newPptTemplate.ppt";
        	}
        	else if(extentFileName.equals("doc")){
        		templateFile = templateFilePath +  "\\" + "newWordTemplate.doc";
        	}
        	else if(extentFileName.equals("vsd")){
        		templateFile = templateFilePath +  "\\" + "NewVisioTemplate.vsd";
        	}
        	else if (extentFileName.equals("mpp")){
        		templateFile = templateFilePath +  "\\" + "NewProjectTemplate.mpp";
        	}
        	else if (extentFileName.equals("jpg")){
        		templateFile = templateFilePath +  "\\" + "NewProjectTemplate.jpg";
        	}
        	else{
        		
        	}
    	}
    	return templateFile;
	}
	
	/**
	 * 判断文件是否能被ntko控件打开
	 * @param fileName 文件名
	 * @return
	 */
	public static boolean isFileCanBeOpenedByNtko(String fileName){
		if(fileName != null && fileName.trim().length() > 0){
//			String extentFileName = getFileFormat(fileName).toLowerCase();
//			String[] ntkoExtentFileNames = new String[]{"doc", "xls", "ppt", "vsd", "mpp"};
//			return ArrayUtils.isExist(extentFileName, ntkoExtentFileNames);
		}
		return false;
	}
	
	/**
	 * 获取NTKO对应的模板文件
	 * @param fileName 文件名
	 * @param templateFilePath 模板文件的绝对路径
	 * @return
	 */
	public static File newTemplateFile(String fileName, String templateFilePath){
        //获取文件的扩展名
        String extentFileName = getFileFormat(fileName);
        //根据文件的扩展名获取模板文件的存放路径
        String templateFileWholePath = getTemplateFileWholePath(extentFileName, templateFilePath);
        return new File(templateFileWholePath);
	}
	
	/**
	 * 处理中文文件名
	 * @param fileName
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static String reEncodeChineseFileName(String fileName, HttpServletRequest request) throws Exception{
		fileName = URLEncoder.encode(fileName , "UTF-8");
        if (fileName.length() > 150) {
            String charset = request.getCharacterEncoding(); //根据request的locale 得出可能的编码
            fileName = new String(fileName.getBytes(charset), "ISO8859-1"); 
        }
        return fileName;
	}
	  // 复制文件
    public static void copyFile(File sourceFile, File targetFile) throws IOException {
        BufferedInputStream inBuff = null;
        BufferedOutputStream outBuff = null;
        try {
            // 新建文件输入流并对它进行缓冲
            inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

            // 新建文件输出流并对它进行缓冲
            outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

            // 缓冲数组
            byte[] b = new byte[1024 * 5];
            int len;
            while ((len = inBuff.read(b)) != -1) {
                outBuff.write(b, 0, len);
            }
            // 刷新此缓冲的输出流
            outBuff.flush();
        } finally {
            // 关闭流
            if (inBuff != null)
                inBuff.close();
            if (outBuff != null)
                outBuff.close();
        }
    }
    public static void main(String[] args) {
    	try {
			copyFile(new File("d:\\demo.doc"),new File( "d:\\demo1.doc"));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
